<?php
namespace Common\Library;
class WxHelper{
	
	private $_ACCESSTOKEN = '';
	public $_POSTOBJ;
	//验证URL正确性的，填微信配置服务器地址的时候用
	public function valid(){
        $echoStr = $_GET["echostr"];
        if($this->checkSignature()){
        	echo $echoStr;
        	exit;
        }
    }

	private function checkSignature(){
        if (!C('TOKEN')) {
            die('TOKEN is not defined!');
        }
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
		$token = C("TOKEN");
		$tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
		sort($tmpArr, SORT_STRING);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}
	
	public function __construct(){
		$this->_ACCESSTOKEN = $this->getAccessToken();
		$this->initMsgPostObj();
	}
	
	public function getAccessToken(){
		$https = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.C('APPID').'&secret='.C('APPSECRET');
		$data = $this->httpGetData($https);
		$accesstoken = $data['access_token'];
		return $accesstoken;
	}
	
	public function delMenu(){
		$https = 'https://api.weixin.qq.com/cgi-bin/menu/delete?access_token='.$this->_ACCESSTOKEN;
		$json = file_get_contents($https);
		$jsonobj = json_decode($json);
		$msg = $jsonobj->errmsg;
		return $msg;
	}
	
	public function getMenu(){
		$https = 'https://api.weixin.qq.com/cgi-bin/get_current_selfmenu_info?access_token='.$this->_ACCESSTOKEN;
		$json = file_get_contents($https);
		$jsonobj = json_decode($json);
		return $jsonobj;
	}
	
	public function setMenu(){
		if(!C('MENU')){
			echo 'menu is empty!';
			exit;
		}
		$https = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$this->_ACCESSTOKEN;
		
		$jsondata = json_encode(C('MENU'),JSON_UNESCAPED_UNICODE);
		
		return $this->httpPostData($https, $jsondata);
		
	}
	
	public function httpPostData($url, $data_string) {  
  
        $ch = curl_init();  
        curl_setopt($ch, CURLOPT_POST, 1);  
        curl_setopt($ch, CURLOPT_URL, $url);  
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);  
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(  
            'Content-Type: application/json; charset=utf-8',  
            'Content-Length: ' . strlen($data_string))  
        );  
        ob_start();  
        curl_exec($ch);  
        $return_content = ob_get_contents();  
        ob_end_clean();  
  
        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);  
        return array($return_code, $return_content);  
    }
    
    public function httpGetData($url){
    	//初始化curl
       	$ch = curl_init();
		//设置超时
		curl_setopt($ch, CURLOPT_TIMEOUT, 30);
		curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
		curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		//运行curl，结果以jason形式返回
        $res = curl_exec($ch);
		curl_close($ch);
		//得到data
		$data = json_decode($res,true);
		return $data;
    }
    
    
	/**
	 * 	作用：格式化参数，签名过程需要使用
	 */
	function formatBizQueryParaMap($paraMap, $urlencode)
	{
		$buff = "";
		ksort($paraMap);
		foreach ($paraMap as $k => $v)
		{
		    if($urlencode)
		    {
			   $v = urlencode($v);
			}
			//$buff .= strtolower($k) . "=" . $v . "&";
			$buff[]= $k . "=" . $v;
		}
		$reqPar = implode('&',$buff);
		return $reqPar;
	}
    
	//用户信息获取
	/**
	 * 	作用：生成可以获得code的url
	 * $scope='snsapi_base'  无需用户授权
	 * $scope='snsapi_userinfo' 弹出窗让用户授权，获得用户用户名等信息
	 */
	function createOauthUrlForCode($redirectUrl,$scope='snsapi_userinfo')
	{
		$urlObj["appid"] = C('APPID');
		$urlObj["redirect_uri"] = "$redirectUrl";
		$urlObj["response_type"] = "code";
		$urlObj["scope"] = $scope;
		$urlObj["state"] = "STATE"."#wechat_redirect";
		$bizString = $this->formatBizQueryParaMap($urlObj, true);
		return "https://open.weixin.qq.com/connect/oauth2/authorize?".$bizString;
	}

	/**
	 * 	作用：生成可以获得openid的url
	 */
	function createOauthUrlForOpenid($code)
	{
		$urlObj["appid"] = C('APPID');
		$urlObj["secret"] = C('APPSECRET');
		$urlObj["code"] = $code;
		$urlObj["grant_type"] = "authorization_code";
		$bizString = $this->formatBizQueryParaMap($urlObj, true);
		return "https://api.weixin.qq.com/sns/oauth2/access_token?".$bizString;
	}
    
	/**
	 * 	作用：通过curl向微信提交code，以获取openid
	 */
	function getOpenid($code)
	{
		$url = $this->createOauthUrlForOpenid($code);
        //初始化curl
       	$ch = curl_init();
		//设置超时
		curl_setopt($ch, CURLOP_TIMEOUT, 30);
		curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
		curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		//运行curl，结果以jason形式返回
        $res = curl_exec($ch);
		curl_close($ch);
		//取出openid
		$data = json_decode($res,true);
		$this->openid = $data['openid'];
		return $this->openid;
	}
    
	/**
	 *获得JS调用的门票
	 *{
		"errcode":0,
		"errmsg":"ok",
		"ticket":"bxLdikRXVbTPdHSM05e5u5sUoXNKd8-41ZO3MhKoyN5OfkWITDGgnr2fwJ0m9E8NYzWKVZvdVtaUgWvsdshFKA",
		"expires_in":7200
		}
	 */
    function getJsApiTicket(){
    	$accesstoken = $this->getAccessToken();
    	$url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.$accesstoken.'&type=jsapi';
    	$data = $this->httpGetData($url);
    	return $data['ticket'];
    }
    
    /**
     * timestamp---时间戳
     * nonceStr--随机字符
     * jsapi_ticket
     * url -----调用页面的地址
     * @param $Obj
     * @return unknown_type
     */
    function getJsSign($parameters){
		$string = $this->formatBizQueryParaMap($parameters, false);
		//签名步骤二：sha1加密
		$string = sha1($string);
		return $string;
    }
    
    /**
     * 消息自动回复
     * 1、根据接收到的消息判断是什么类型
     * 2、根据接收到的消息来确认回复什么信息
     * Enter description here ...
     */
    function responseMsg(){
    //get post data, May be due to the different environments
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
      	//extract post data
		if (!empty($postStr)){
                /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
                   the best way is to check the validity of xml by yourself */
                libxml_disable_entity_loader(true);
              	$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
                $fromUsername = $postObj->FromUserName;
                $toUsername = $postObj->ToUserName;
                $keyword = trim($postObj->Content);
                $time = time();
                //文字模板
                $textTpl = "<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<Content><![CDATA[%s]]></Content>
							</xml>";
                //图文模板 
                $newsTpl = <<<eof
						    <xml>
								<ToUserName><![CDATA[%s]]></ToUserName>
								<FromUserName><![CDATA[%s]]></FromUserName>
								<CreateTime>%s</CreateTime>
								<MsgType><![CDATA[news]]></MsgType>
								<ArticleCount>2</ArticleCount>
								<Articles>
									<item>
										<Title><![CDATA[sffdsf]]></Title> 
										<Description><![CDATA[sfasdfqe]]></Description>
										<PicUrl><![CDATA[http://laichuhan.com/app/laichuhan/upload/images/article/14461121860.jpg]]></PicUrl>
										<Url><![CDATA[http://laichuhan.com/app/laichuhan/upload/images/article/14461121860.jpg]]></Url>
									</item>
									<item>
										<Title><![CDATA[sfdsf]]></Title>
										<Description><![CDATA[xxxxxxxsfsfsf]]></Description>
										<PicUrl><![CDATA[http://laichuhan.com/app/laichuhan/upload/images/article/14461121860.jpg]]></PicUrl>
										<Url><![CDATA[http://laichuhan.com/app/laichuhan/upload/images/article/14461121860.jpg]]></Url>
									</item>
								</Articles>
							</xml>            
eof;
$resultStr = sprintf($piclist, $fromUsername, $toUsername, $time);
echo $resultStr;
				
//				if(!empty( $keyword ))
//                {
//              		$msgType = "text";
//                	$contentStr = "Welcome to wechat world!";
//                	$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
//                	echo $resultStr;
//                }else{
//                	echo "Input something...";
//                }

        }else {
        	echo "";
        	exit;
        }
    }
    
    /**
     * 初始化微信POST过来的消息
     * Enter description here ...
     */
    public function initMsgPostObj(){
    	$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
    	if (!empty($postStr)){
    		libxml_disable_entity_loader(true);
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $this->_POSTOBJ = $postObj;
    	}
    }
    
    public function getMsgPostFromUsername(){
    	if(!empty($this->_POSTOBJ)){
	    	return $this->_POSTOBJ->FromUserName;
    	}
    }
	public function getMsgPostToUsername(){
		if(!empty($this->_POSTOBJ)){
    		return $this->_POSTOBJ->ToUserName;
		}
    }
	public function getMsgPostKeyword(){
		if(!empty($this->_POSTOBJ)){
			return trim($this->_POSTOBJ->Content);
		}
    }
    public function getMsgPostMsgType(){
   	 if(!empty($this->_POSTOBJ)){
			return trim($this->_POSTOBJ->MsgType);
		}
    }
    
	public function getMsgPostLat(){
   	 	if(!empty($this->_POSTOBJ)){
			return trim($this->_POSTOBJ->Location_X);
		}
    }
	public function getMsgPostLng(){
   	 	if(!empty($this->_POSTOBJ)){
			return trim($this->_POSTOBJ->Location_Y);
		}
    }
	public function getMsgPostLabel(){
   	 	if(!empty($this->_POSTOBJ)){
			return trim($this->_POSTOBJ->Label);
		}
    }
    //上报地理位置
    public function getMsgPostLocation(){
   	 	if(!empty($this->_POSTOBJ)){
   	 		return array('lat'=>$this->_POSTOBJ->Latitude,'lng'=>$this->_POSTOBJ->Longitude);
		}
    }
	public function getMsgPostEvent(){
   	 	if(!empty($this->_POSTOBJ)){
			return trim($this->_POSTOBJ->Event);
		}
    }
    public function getMsgPostEventKey(){
    	if(!empty($this->_POSTOBJ)){
			return trim($this->_POSTOBJ->EventKey);
		}
    }
	public function getMsgPostMsgId(){
    	if(!empty($this->_POSTOBJ)){
			return trim($this->_POSTOBJ->MsgId);
		}
    }
    //获得声音消息的关键字
    public function getMsgPostVoiceCont(){
    	if(!empty($this->_POSTOBJ)){
			return trim($this->_POSTOBJ->Recognition);
		}
    }
    
    public function getMsgPostSendLocationInfo(){
    	if(!empty($this->_POSTOBJ)){
			return trim($this->_POSTOBJ->SendLocationInfo);
		}
    }
    
    
    
    
    
    /**
     * 回复文字消息
     * 传入需要回复的文字内容即可
     * @param unknown_type $content
     */
    public function responseMsgText($content){
    	$fromUsername = $this->getMsgPostFromUsername();
    	if(empty($fromUsername)){return false;}
        $toUsername = $this->getMsgPostToUsername();
        $keyword = $this->getMsgPostKeyword();
        $time = time();
        //文字模板
        $textTpl = <<<eof
        	<xml>
				<ToUserName><![CDATA[$fromUsername]]></ToUserName>
				<FromUserName><![CDATA[$toUsername]]></FromUserName>
				<CreateTime>$time</CreateTime>
				<MsgType><![CDATA[text]]></MsgType>
				<Content><![CDATA[$content]]></Content>
			</xml>
eof;
		echo $textTpl;
    }
    
    /**
     * 回复图文消息
     * 传入需要回复的文字内容即可
     * @param unknown_type $content
     */
    public function responseMsgNews($list){
    	$fromUsername = $this->getMsgPostFromUsername();
    	if(empty($fromUsername)){return false;}
        $toUsername = $this->getMsgPostToUsername();
        $keyword = $this->getMsgPostKeyword();
        $time = time();
        $count = count($list);
        if(empty($list)){return false;}
        foreach ($list as $d){
        	$title = $d['title'];
        	$tips = $d['tips'];
        	$url = $d['href'];
        	$pic = $d['pic'];
        	$item .= <<<eof
        	<item>
				<Title><![CDATA[$title]]></Title> 
				<Description><![CDATA[$tips]]></Description>
				<PicUrl><![CDATA[$pic]]></PicUrl>
				<Url><![CDATA[$url]]></Url>
			</item>
eof;
        }
        //图文模板
        $newsTpl = <<<eof
        	<xml>
				<ToUserName><![CDATA[$fromUsername]]></ToUserName>
				<FromUserName><![CDATA[$toUsername]]></FromUserName>
				<CreateTime>$time</CreateTime>
				<MsgType><![CDATA[news]]></MsgType>
				<ArticleCount>$count</ArticleCount>
				<Articles>
					$item
				</Articles>
			</xml>
eof;
		echo $newsTpl;
    }
    
    
}
?>